package com.hhf.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.springboot.common.DataGroupByDateDTO;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.constant.CommonConstant;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.mapper.ServiceProjectMapper;
import com.hhf.springboot.model.dto.serviceProject.ServiceProjectQueryRequest;
import com.hhf.springboot.model.entity.ServiceProject;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.vo.ServiceProjectVO;
import com.hhf.springboot.model.vo.UserVO;
import com.hhf.springboot.service.ServiceProjectService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.DateUtils;
import com.hhf.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 服务项目信息服务实现
 *
 * @author hhf
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@Service
@Slf4j
public class ServiceProjectServiceImpl extends ServiceImpl<ServiceProjectMapper, ServiceProject> implements ServiceProjectService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param serviceProject
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validServiceProject(ServiceProject serviceProject, boolean add) {
        ThrowUtils.throwIf(serviceProject == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String title = serviceProject.getTitle();
        String introduce = serviceProject.getIntroduce();
        Integer price = serviceProject.getPrice();

        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title,introduce), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(introduce)) {
            ThrowUtils.throwIf(title.length() > 8000, ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (price != null && price < 0 ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "价格不能低于0");
        }

    }

    /**
     * 获取查询条件
     *
     * @param serviceProjectQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<ServiceProject> getQueryWrapper(ServiceProjectQueryRequest serviceProjectQueryRequest) {
        QueryWrapper<ServiceProject> queryWrapper = new QueryWrapper<>();
        if (serviceProjectQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = serviceProjectQueryRequest.getId();
        String title = serviceProjectQueryRequest.getTitle();
        String introduce = serviceProjectQueryRequest.getIntroduce();
        Integer status = serviceProjectQueryRequest.getStatus();
        Long userId = serviceProjectQueryRequest.getUserId();
        String sortField = serviceProjectQueryRequest.getSortField();
        String sortOrder = serviceProjectQueryRequest.getSortOrder();
        // 补充需要的查询条件
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(introduce), "introduce", introduce);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);

        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                StrUtil.toUnderlineCase(sortField));

        return queryWrapper;
    }

    /**
     * 获取服务项目信息封装
     *
     * @param serviceProject
     * @param request
     * @return
     */
    @Override
    public ServiceProjectVO getServiceProjectVO(ServiceProject serviceProject, HttpServletRequest request) {
        // 对象转封装类
        ServiceProjectVO serviceProjectVO = ServiceProjectVO.objToVo(serviceProject);

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = serviceProject.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        serviceProjectVO.setUser(userVO);
        // endregion

        return serviceProjectVO;
    }

    /**
     * 分页获取服务项目信息封装
     *
     * @param serviceProjectPage
     * @param request
     * @return
     */
    @Override
    public Page<ServiceProjectVO> getServiceProjectVOPage(Page<ServiceProject> serviceProjectPage, HttpServletRequest request) {
        List<ServiceProject> serviceProjectList = serviceProjectPage.getRecords();
        Page<ServiceProjectVO> serviceProjectVOPage = new Page<>(serviceProjectPage.getCurrent(), serviceProjectPage.getSize(), serviceProjectPage.getTotal());
        if (CollUtil.isEmpty(serviceProjectList)) {
            return serviceProjectVOPage;
        }
        // 对象列表 => 封装对象列表
        List<ServiceProjectVO> serviceProjectVOList = serviceProjectList.stream().map(serviceProject -> {
            return ServiceProjectVO.objToVo(serviceProject);
        }).collect(Collectors.toList());

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = serviceProjectList.stream().map(ServiceProject::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        serviceProjectVOList.forEach(serviceProjectVO -> {
            Long userId = serviceProjectVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            serviceProjectVO.setUser(userService.getUserVO(user));
        });
        // endregion

        serviceProjectVOPage.setRecords(serviceProjectVOList);
        return serviceProjectVOPage;
    }

    /**
    * 分按日期分组查询服务项目信息新增数量
    *
    * @param beginDate 开始时间
    * @param endDate   结束时间
    * @return
    */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<ServiceProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(),DateUtils.FMT_YMD));
            dto.setNum(((Number) result.get("num")).intValue()); // 修改为Integer类型
            return dto;
        }).collect(Collectors.toList());
    }


    @Override
    public long doClick(Long serviceProjectId) {
        // 判断实体是否存在，根据类别获取实体
        ServiceProject serviceProject = this.getById(serviceProjectId);
        if (serviceProject == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //浏览数+1
        this.update().eq("id", serviceProjectId).setSql("click_num = click_num + 1").update();
        return serviceProject.getClickNum() + 1;
    }

}
